package com.id.supaclean.ui

import android.os.Bundle
import android.util.Log
import android.view.View
import android.widget.FrameLayout
import android.widget.ImageView
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import androidx.fragment.app.Fragment
import androidx.fragment.app.FragmentTransaction
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.lifecycleScope
import com.id.supaclean.R
import com.id.supaclean.ktx.repeatOnLifecycle
import com.id.supaclean.utils.Events
import com.id.supaclean.widget.SubSku
import com.id.supaclean.widget.UserCanceledPayException
import com.id.supaclean.widget.pay
import kotlinx.coroutines.flow.catch
import kotlinx.coroutines.flow.collectLatest
import kotlinx.coroutines.launch

class PurchaseActivity : AppCompatActivity() {
    val fragmentManager = supportFragmentManager
    var retainFragment = RetainFragment()
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_purchase)



        findViewById<ImageView>(R.id.weekly_btn).setOnClickListener {
            purchaseWeekly()
        }
        findViewById<ImageView>(R.id.cancel_button).setOnClickListener {
            finish()
        }
        findViewById<ImageView>(R.id.purchase_button).setOnClickListener {
            purchaseWeekly()
        }

    }



    private fun openFragment(fragment: Fragment, tag: String) {
        val fragmentTransaction: FragmentTransaction = fragmentManager.beginTransaction()
        fragmentTransaction.replace(R.id.retainFragment, fragment, tag)
        //添加到返回按键堆栈，这样就可以执行碎片的第二条周期，也就是不会每次replace的时候都去执行onAttach
        fragmentTransaction.addToBackStack(null)
        fragmentTransaction.commit()
    }

    fun purchaseWeekly() {
        lifecycleScope.launch {
            repeatOnLifecycle(Lifecycle.State.STARTED) {
                pay(SubSku.SkuWeekly).catch { e ->
                    if (e !is UserCanceledPayException) {
                        Events.sendEvent(
                            "v_sub_fail_${SubSku.SkuWeekly.skuId}",
                            "reason" to e.message
                        )
                        Toast.makeText(
                            this@PurchaseActivity,
                            "Network Error",
                            Toast.LENGTH_SHORT
                        ).show()
                    } else {
                        Events.sendEvent("canceled_paywall_${SubSku.SkuWeekly.skuId}")
                        openFragment(retainFragment, "1")
                        findViewById<FrameLayout>(R.id.retainFragment).visibility = View.VISIBLE
                    }
                }.collectLatest {
                    Events.sendEvent("v_sub_seccessful_${SubSku.SkuWeekly.skuId}")
                }
            }
        }
    }
}